<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="关键字"
            clearable
            @keyup.enter="handleSearch()"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch()">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery()">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="flex flex-col h-full" body-style="height: calc(100% - 40px);">
      <el-tabs v-model="activeName" class="enter-tabs" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="item in messageTypeList"
          :key="item.value"
          :label="item.label"
          :name="item.value"
        >
          <template #label="scope">
            <el-badge :value="item.count" :max="99">{{ item.label }}</el-badge>
          </template>
        </el-tab-pane>
      </el-tabs>

      <base-page-table
        :table-data="pageData"
        :table-columns-data="tableColumnsData"
        :loading="loading"
        :page-num="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        :total="total"
        class="h-full"
        @handleQuery="handlePageChange"
      >
        <template #type="{ row, name }">
          {{ getLabelByValue(MESSAGE_TYPE_ENUM, row.type) }}
        </template>
        <template #level="{ row, name }">
          <el-tag :type="MESSAGE_LEVEL_ENUM_MAP[row.level] || 'primary'">
            {{ getLabelByValue(MESSAGE_LEVEL_ENUM, row.level) }}
          </el-tag>
        </template>
        <template #isRead="{ row, name }">
          <el-tag v-if="row.isRead == 1" type="success">已读</el-tag>
          <el-tag v-else type="info">未读</el-tag>
        </template>
        <template #handle="scope">
          <el-button type="primary" size="small" link @click="viewNoticeDetail(scope.row)">
            查看
          </el-button>
        </template>
      </base-page-table>
    </el-card>

    <NoticeDetail ref="noticeDetailRef" />
  </div>
</template>

<script setup lang="ts">
import {
  IS_READ_ENUM,
  MARK_TYPE_ENUM,
  MESSAGE_LEVEL_ENUM,
  MESSAGE_LEVEL_ENUM_MAP,
  MESSAGE_TYPE_ENUM,
  PUBLISH_STATUS_ENUM,
} from "@/enums/notice/NoticeEnum";

defineOptions({
  name: "MyNotice",
  inheritAttrs: false,
});

import NoticeAPI, { NoticePageVO, NoticePageQuery } from "@/api/system/notice";
import { getLabelByValue, getLabelValueList } from "@/utils/enums";
const queryFormRef = ref();
const noticeDetailRef = ref();

const pageData = ref<NoticePageVO[]>([]);
const tableColumnsData = ref([
  {
    type: "index",
    label: "序号",
    width: 60,
    align: "center",
  },
  {
    width: 200,
    label: "标题",
    prop: "title",
    align: "center",
    showOverflowTooltip: true,
  },
  {
    label: "消息类型",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "type",
  },
  {
    label: "紧急程度",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "level",
  },
  {
    label: "发布时间",
    align: "center",
    showOverflowTooltip: true,
    prop: "fmtPublishTime",
  },
  {
    label: "发布人",
    align: "center",
    showOverflowTooltip: true,
    prop: "publisherName",
  },
  {
    label: "状态",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "isRead",
  },

  {
    width: 200,
    label: "操作",
    prop: "handle",
    fixed: "right",
    align: "center",
    showOverflowTooltip: true,
    customSlot: "handle",
  },
]);
const noticeStat = ref({});

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<NoticePageQuery>({
  pageNum: 1,
  pageSize: 10,
  publishStatus: PUBLISH_STATUS_ENUM.PUBLISHED.value,
});

const activeName = ref("");
const messageTypeList = computed(() => {
  const map = {
    [MESSAGE_TYPE_ENUM.SYSTEM.value]: "systemCount",
    [MESSAGE_TYPE_ENUM.PRODUCT.value]: "productCount",
    [MESSAGE_TYPE_ENUM.FINANCE.value]: "financeCount",
    [MESSAGE_TYPE_ENUM.ACTIVITY.value]: "activityCount",
    [MESSAGE_TYPE_ENUM.SECURITY.value]: "safetyCount",
  };
  return [
    {
      label: "全部消息",
      value: "",
      count: noticeStat.value.total || 0,
    },
    ...getLabelValueList(MESSAGE_TYPE_ENUM).map((item) => {
      item.count = noticeStat.value[map[item.value]] || 0;
      return item;
    }),
  ];
});

function handleTabClick() {
  handleQuery();
}
function handlePageChange({ pageNum, pageSize }) {
  queryParams.pageNum = pageNum;
  queryParams.pageSize = pageSize;
  handleQuery();
}
async function getMyNoticeStat() {
  try {
    const res = await NoticeAPI.getMyNoticeStatApi({ isRead: IS_READ_ENUM.UNREAD.value });
    noticeStat.value = res;
  } catch (e) {
    console.log(e);
  }
}
/** 查询通知公告 */
function handleQuery() {
  // loading.value = true;
  // NoticeAPI.getMyNoticePage({
  //   ...queryParams,
  //   types: (activeName.value && [activeName.value]) || [],
  // })
  //   .then((data) => {
  //     pageData.value = data.list || [];
  //     total.value = data.total;
  //   })
  //   .finally(() => {
  //     loading.value = false;
  //   });
}

async function markAsRead(id) {
  try {
    await NoticeAPI.readAll({
      noticeId: id,
      markType: MARK_TYPE_ENUM.SINGLE_READ.value,
    });
  } catch (e) {
    console.log(e);
  }
}

/** 重置通知公告查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  activeName.value = "";
  handleQuery();
}

function handleSearch() {
  queryParams.pageNum = 1;
  handleQuery();
  getMyNoticeStat();
}

async function viewNoticeDetail(row) {
  noticeDetailRef.value.openNotice(row.id);
  if (row.isRead === IS_READ_ENUM.UNREAD.value) {
    await markAsRead(row.id);
    handleQuery();
    getMyNoticeStat();
  }
}

onMounted(() => {
  handleQuery();
  getMyNoticeStat();
});
</script>
